/**
 * Copyright (c) 2015-2019, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.jfsa.manage.controller.module.cases;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

import cn.hg.base.jfinal.controller.BaseController;
import cn.hg.base.kit.StrExtKit;
import cn.hg.jfsa.core.JfsaThreadLocal;
import cn.hg.jfsa.manage.controller.module.cases.validator.CasesValidator;
import cn.hg.jfsa.manage.service.CasesService;
import cn.hg.jfsa.manage.web.LayuiPage;
import cn.hg.jfsa.model.Cases;
import cn.hg.jfsa.model.CasesImage;
import cn.hg.jfsa.model.JfsaAdmin;
import cn.hg.jfsa.web.theme.ThemeManager;

/**
 * @author Golly
 */
public class CasesController extends BaseController {

	@Inject
	private CasesService casesService;

	/**
	 * 跳转到新增页面
	 */
	public void add () {
		// 创建新记录
		this.setAttr("cases",
			new Cases().setHits(0).setBaseHits(Math.abs(new Random().nextInt() % 1000)).setStatus("off"));
		this.setAttr("casesCategoryList", this.casesService.getCasesCategoryList());
		this.setAttr("casesImageList", new ArrayList<CasesImage>());
	}

	/**
	 * Ajax删除功能
	 */
	@Before (EvictInterceptor.class)
	@CacheName ("cases")
	public void ajaxDel () {
		// 通过页面传入的ID查找到记录
		Cases bean = Cases.DAO.findById(this.getParaToInt("id"));

		// 记录不存在则报错
		if (null == bean) {
			this.renderAjaxFailed("1", "记录不存在！");
			return;
		}

		// 更新记录的状态为删除
		bean.setStatus("del").update();
		// 返回Ajax成功
		this.renderAjaxSuccessed();
	}

	/**
	 * Ajax方式新建或更新记录O
	 */
	@Before ({
		CasesValidator.class, EvictInterceptor.class
	})
	@CacheName ("cases")
	public void ajaxSaveOrUpdate () {
		// 获取页面传入的Bean
		Cases bean = this.getBean(Cases.class, "cases");
		JfsaAdmin currAdmin = JfsaThreadLocal.getAdmin();
		// 这里引用事务处理是为了方便Ajax模式处理
		boolean successed = Db.tx(new IAtom() {

			@Override
			public boolean run () throws SQLException {

				if (null == bean.getId()) {
					// 初始化数据
					bean.setTheme(ThemeManager.me().getCurrentTheme().getId())
						.setCreatedTime(new Date())
						.setCreatorId(currAdmin.getId())
						.setEditorId(currAdmin.getId())
						.setEditedTime(new Date())
						.save();
				} else {

					if (1 == bean.getId()) { // ID为1的案例状态必须为on
						bean.setStatus("on");
					}

					// 更新记录
					bean.setEditorId(currAdmin.getId())
						.setEditedTime(new Date())
						.update();
				}

				// 更新案例图片
				CasesController.this.updateCaseImages(bean);
				return true;
			}

		});

		// 返回Ajax成功
		if (successed) {
			this.renderAjaxSuccessed();
		} else {
			this.renderAjaxFailed("1", "操作失败！");
		}

	}

	/**
	 * Ajax方式查询
	 */
	@Before (CacheInterceptor.class)
	@CacheName ("cases")
	public void ajaxSearch () {
		// 建立查询键值对
		Kv para = Kv.by("code", this.getPara("code"))
			.set("title", this.getPara("title"))
			.set("subtitle", this.getPara("subtitle"))
			.set("category", this.getPara("category"))
			.set("status", this.getPara("status"))
			.set("sortField", StrExtKit.humpToUnderline(this.getPara("sortField")))
			.set("sortType", this.getPara("sortType"))
			.set("theme", ThemeManager.me().getCurrentTheme().getId());
		// 通过SQL模板引擎构建SQL及参数
		SqlPara sqlPara = Db.getSqlPara("module.findCases", para);
		// 执行查询
		Page<Cases> page = Cases.DAO.paginate(this.getParaToInt("page", 1), this.getParaToInt("limit", 10), sqlPara);
		this.setAttr("sortField", this.getPara("sortField"));
		this.setAttr("sortType", this.getPara("sortType"));
		// 返回Ajax调用的Json结果
		this.renderJson(new LayuiPage(page));
	}

	/**
	 * 跳转到编辑页面
	 */
	public void edit () {
		// 查询目标记录
		Cases bean = Cases.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		this.setAttr("cases", bean);
		this.setAttr("casesImageList", this.casesService.getCasesImageList(bean.getId()));
		this.setAttr("casesCategoryList", this.casesService.getCasesCategoryList());
	}

	/**
	 * 跳转到列表页面
	 */
	@Override
	@Before (CacheInterceptor.class)
	@CacheName ("cases")
	public void index () {
		this.setAttr("casesCategoryList", this.casesService.getCasesCategoryList());
	}

	/**
	 * 跳转到查看页面
	 */
	@Before (CacheInterceptor.class)
	@CacheName ("cases")
	public void view () {
		// 查询目标记录
		Cases bean = Cases.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		this.setAttr("cases", bean);
		this.setAttr("casesImageList", this.casesService.getCasesImageList(bean.getId()));
		this.setAttr("casesCategoryList", this.casesService.getCasesCategoryList());
	}

	private Integer[] getParaValuesToInt (String paraName, Integer size) {
		Integer[] values = new Integer[size];

		for (int i = 0; i < size; i++) {
			values[i] = this.getParaToInt(paraName + "[" + i + "]");
		}

		return values;
	}

	private String[] getParaValuesToString (String paraName, Integer size) {
		String[] values = new String[size];

		for (int i = 0; i < size; i++) {
			values[i] = this.getPara(paraName + "[" + i + "]");
		}

		return values;
	}

	private void updateCaseImages (Cases c) {
		int imgSize = this.getParaToInt("casesImgSize");
		Integer[] ids = this.getParaValuesToInt("imgIds", imgSize);
		String[] devices = this.getParaValuesToString("devices", imgSize);
		String[] images = this.getParaValuesToString("images", imgSize);
		String[] status = this.getParaValuesToString("status", imgSize);
		Integer[] sortNums = this.getParaValuesToInt("sortNums", imgSize);

		for (int i = 0; i < imgSize; i++) {

			switch (status[i]) {
				case "new":
					new CasesImage()
						.setCasesId(c.getId())
						.setDevice(devices[i])
						.setImg(images[i])
						.setSortNum(sortNums[i])
						.save();
					break;

				case "old":
				case "change":
					CasesImage.DAO.findById(ids[i])
						.setImg(images[i])
						.setDevice(devices[i])
						.setSortNum(sortNums[i])
						.update();
					break;

				case "remove":
					CasesImage.DAO.findById(ids[i]).delete();
					break;

				default:
					break;
			}

		}

	}

}
